<?php

namespace Anchu\Restful\Runner\Decorates;

/**
 * 锁定每次查询或者操作的时候的user_id
 *
 * @package Anchu\Restful\Runner\Decorates
 */
class FilterUserIdDecorate extends FilterDecorate
{

    /**
     * 要求返回Filter对象
     * @param $filter Filter
     * @return Filter
     */
    public function run(Filter $filter): Filter
    {
        // 前台应用
        if ($this->isAuthed() && $this->isApi()) {
            $filter->where[] = ['user_id', '=', auth('api')->user()->getAuthIdentifier()];
        }
        // 后台应用
        if ($this->isAuthed() && $this->isAdmin()) {
            $filter->where[] = ['admin_id', '=', auth('admin')->user()->getAuthIdentifier()];
        }
        return $filter;
    }

    public function isApi(): bool
    {
        if (str_starts_with(strtolower(request()->path()), 'api/')) {
            return true;
        }
        return false;
    }

    public function isAdmin(): bool
    {
        if (str_starts_with(strtolower(request()->path()), 'admin/')) {
            return true;
        }
        return false;
    }


    public function isAuthed(): bool
    {
        return !is_null(auth('api')->user());
    }
}
